import { Inject, Injectable, Injector } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, CanActivateChild, Router, RouterStateSnapshot } from '@angular/router';
import { sysConf } from '@conf/sys.conf';
import { CoreService } from '@core';
import { ACLGuard, ACLService } from '@delon/acl';
import { EAUserService } from '@shared';
import { Observable, of } from 'rxjs';

@Injectable()
export class EATokenGuard implements CanActivate, CanActivateChild {
  constructor(srv: ACLService, router: Router, private eaUserSrv: CoreService, private router2: Router, private inject: Injector) {}

  canActivate(route: ActivatedRouteSnapshot, _state: RouterStateSnapshot | null): Observable<boolean> {
    const canOpen = this.eaUserSrv.loginStatus;
    if (!canOpen) {
      this.router2.navigate([sysConf.login_url], {
        queryParams: {
          returnUrl: _state?.url
        }
      });
      return of(!canOpen);
    }
    return of(true);
  }

  canActivateChild(childRoute: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
    const canOpen = this.eaUserSrv.loginStatus;
    if (!canOpen) {
      this.router2.navigate([sysConf.login_url], {
        queryParams: {
          returnUrl: state?.url
        }
      });
      return of(!canOpen);
    }
    return of(true);
  }
}
